package com.youzhi.backend.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * spring 项目初始化完毕执行
 *
 * @author mengxu
 */
@Slf4j
@Component
public class ProjectInitConfig implements CommandLineRunner {


    @Autowired
    private SecurityManager securityManager;

    @Autowired
    private RedisSessionDao redisSessionDao;

    @Autowired
    private Realm realm;


    @Autowired
    private Environment environment;

    @Override
    public void run(String... args) throws Exception {

        //设置securityManager设置参数
        settingSecurityManager();

        //设置SecurityManager到全局变量
        initStaticSecurityManager();

        //打印swagger页面地址
        printSwaggerAddr();


    }

    private void printSwaggerAddr() {
        log.info("启动成功，swagger地址：http://" + getIpAddr() + ":" + environment.getProperty("server.port") + "/swagger-ui.html");
    }

    private void settingSecurityManager() {
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) this.securityManager;

        //设置全局session超时时间为30天
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setGlobalSessionTimeout(ShiroConfig.session_milliseconds_time_out);

        //设置sessionDao
        sessionManager.setSessionDAO(redisSessionDao);

        //设置sessionManager
        securityManager.setSessionManager(sessionManager);

        //设置 realm
        securityManager.setRealm(realm);
    }


    private void initStaticSecurityManager() {
        SecurityUtils.setSecurityManager(securityManager);
    }


    public static String getIpAddr() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            return "未知";
        }
    }

}
